var vaRound = 0;
var vaStatusButton = "";
$(function () {
	// loading province
	loadProvince(true);
	loadRequestType();
	setTimeout(function (){setDefaultAddress();}, 300);
	// load district when province change
	$("select#inputProvinceCode").change(function() {
		loadDistrict(true);
	 });
	// load city when district change
	$("select#inputDistrictCode").change(function() {
		loadCityCode(true);
	 });
});

//set Default Address
function setDefaultAddress(){	
	$.getJSON('CS62000Srvl', { vaDefaultAddress: "yes" }, function(result) {
		$("#inputProvinceCode").val(result.vaDataFromObject[0]);
		$("#inputPostCode").val(result.vaDataFromObject[3]);
		setDistrict(result.vaDataFromObject[1]);
		setCityCode(result.vaDataFromObject[2],result.vaDataFromObject[0],result.vaDataFromObject[1]);
		
		
	});
}

//set Is calculate to default
function changeRequestType(){
	calculateOnSelected('vaCalculate',1);
}

//Set Success,Error massage
function hideSuccessAndErrorMassagse(){
	$('#error_message').addClass('hide');
	$('#success_message').addClass('hide');
}

function clearForm(){
	document.getElementById("divCalculate").innerHTML = "<div id='divCalculate' class='form-group'></div>";
	$("#frm2")[0].reset();
	$("#frm1")[0].reset();
	document.getElementById("vaUseWaterName").innerHTML = "";
	document.getElementById("vaAddress").innerHTML = "";
	document.getElementById("vaMeterSize").innerHTML = "";
	var options1 = '<option value="">-- เลือกตำบล --</option>';
	$("select#inputCityCode").html(options1);
	var options2 = '<option value="">-- เลือกอำเภอ--</option>';
	$("select#inputDistrictCode").html(options2);
}
//------- find Request
function findByRequestNumber(){
	hideSuccessAndErrorMassagse();
	vaStatusButton = "search_by_request";
	var vaRequestType = $('#inputRequestType').val();
	var vaAccount = document.getElementById("inputAccont").value;
	$.getJSON('CS62000Srvl', { btn_search_requestNumber: "yes", inputRequestNumberPassJSon: $("#inputRequestNumber").val(), inputAccountPassJSon: vaAccount,dwlRequestType: vaRequestType}, function(result) {	
		if (result.vaNotExistStatus == 'no'){
			clearForm();
			document.getElementById("btn_search_account").value = "yes";
			$("#inputAccont").val(result.vaDataFromObject[0]);
			document.getElementById("inputAccont").disabled = true;
			$("#hddVaUseWaterPname").val(result.vaDataFromObject[1]);
			$("#hddVaUseWaterFname").val(result.vaDataFromObject[2]);
			$("#hddVaUseWaterLname").val(result.vaDataFromObject[3]);
			$("#hddVaAddress").val(result.vaDataFromObject[4]);
			document.getElementById("vaUseWaterName").innerHTML = result.vaDataFromObject[1]+" "+result.vaDataFromObject[2]+" "+result.vaDataFromObject[3];
			document.getElementById("vaAddress").innerHTML = result.vaDataFromObject[4];
			document.getElementById("vaMeterSize").innerHTML = result.vaDataFromObject[5];
			$("#inputFName").val(result.vaDataFromObject[6]);
			$("#inputHomeNumber").val(result.vaDataFromObject[7]);
			$("#inputAddress").val(result.vaDataFromObject[8]);
			$("#inputProvinceCode").val(result.vaDataFromObject[11]);
			setDistrict(result.vaDataFromObject[10]);
			setCityCode(result.vaDataFromObject[9],result.vaDataFromObject[11],result.vaDataFromObject[10]);
			$("#inputPostCode").val(result.vaDataFromObject[12]);
			$("#inputContactTelephone").val(result.vaDataFromObject[13]);
			$("#inputRequestType").val(result.vaDataFromObject[14]);
			$("#txtAreaDescription").val(result.vaDataFromObject[15]);	
			if ( result.messages.length != 0){
				$("input[name=rdo1][value=vaCalculate]").prop('checked', true);
				writeHtmlDiv(result);			
			} else {
				$("input[name=rdo1][value=" + vaNotCalculate + "]").prop('checked', true);
			}
			hideSuccessAndErrorMassagse();
		} else {
			$("html,body").animate({scrollTop: 0}, 100);  
			document.getElementById("inputAccont").disabled = false;
			document.getElementById("msgError").innerHTML = "ไม่พบรายการเลขที่คำร้อง กรุณาตรวจสอบความถูกต้องของข้อมูล";
			$('#error_message').removeClass('hide');
			clearForm();
		}	
	});
}

//------- find customer by account
function findCustomerByAccount(button){
	hideSuccessAndErrorMassagse();
	vaStatusButton = "search_by_account";
	document.getElementById("btn_search_account").value = "yes";
	var vaAccount = document.getElementById("inputAccont").value;
	$.getJSON('CS62000Srvl', { btn_search_account: "yes", inputAccountPassJSon: vaAccount }, function(result) {
		if ( result.vaNotExistStatus == "no"){
			document.getElementById("vaUseWaterName").innerHTML = result.values[0]+" "+result.values[1]+" "+result.values[2];	
			document.getElementById("vaMeterSize").innerHTML = result.values[4];
			document.getElementById("hddVaUseWaterPname").value = result.values[0];
			document.getElementById("hddVaUseWaterFname").value = result.values[1];
			document.getElementById("hddVaUseWaterLname").value = result.values[2];
			document.getElementById("hddVaAddress").value = result.values[3];	
			var vaCityTemp = result.values[7].split(':');
			document.getElementById("hddVaCityCode").value = vaCityTemp[0];
			var vaDistrictTemp = result.values[6].split(':');
			document.getElementById("hddVaDistrict").value = vaDistrictTemp[0];
			var vaProvinceTemp = result.values[5].split(':');
			document.getElementById("hddVaProvince").value = vaProvinceTemp[0];		
			document.getElementById("hddVaPostCode").value = result.values[8];
			document.getElementById("vaAddress").innerHTML = result.values[3]+" "+vaCityTemp[1]+" "+vaDistrictTemp[1]+" "+vaProvinceTemp[1]+" "+result.values[8];
			document.getElementById("hddVaMeterSize").value = result.values[4];			
			hideSuccessAndErrorMassagse();
		} else {
			 $("html,body").animate({scrollTop: 0}, 100);  
			clearForm();
			document.getElementById("msgError").innerHTML = "ไม่พบทะเบียนผู้ใช้น้ำ กรุณาตรวจสอบความถูกต้องของข้อมูล";
			$('#error_message').removeClass('hide');
		}
	});
}

function saveData(){
	hideSuccessAndErrorMassagse();
	$("#inputAccont").popover('destroy');
	var btnSearchByAccount = document.getElementById("btn_search_account").value;
	if ( btnSearchByAccount == "yes"){
		if ( validateForm() == true ){
			var vaReceiveCode = "";
			for (var i = 0; i < vaRound; i++){
				vaReceiveCode +=  $('#hiddenReceiveCode'+i).val()+"/"+$('#inputFee'+i).val()+",";
			}
			$.getJSON('CS62000Srvl', { btn_save: "yes",
				 vaAccount: $("#inputAccont").val(),
				 dwlRequestType: $("#inputRequestType").val(),
				 vaApplicantName: $("#inputFName").val(),
				 vaDescription: $("#txtAreaDescription").val(),
				 vaContactHomeNumber: $("#inputHomeNumber").val(),
				 vaVillage: $("#inputAddress").val(),
				 vaSubDistrict: $("#inputCityCode").val(),
				 vaSubDistrict2: $("#hddVaCityCode").val(),
				 vaDistrict: $("#inputDistrictCode").val(),
				 vaDistrict2: $("#hddVaDistrict").val(),
				 vaProvince: $("#inputProvinceCode").val(),
				 vaProvince2: $("#hddVaProvince").val(),
				 vaPostCode: $("#inputPostCode").val(),
				 vaPostCode2: $("#hddVaPostCode").val(),
				 vaContactTelephone: $("#inputContactTelephone").val(),
				 vaInputFeeAndAmount: vaReceiveCode,
				 vaPName: $("#hddVaUseWaterPname").val(),
				 vaFName: $("#hddVaUseWaterFname").val(),
				 vaLName: $("#hddVaUseWaterLname").val(),
				 vaAddress: $("#hddVaAddress").val(),
				 vaMeterSize: $("#hddVaMeterSize").val(),
				 vaRequestNumber:$("#inputRequestNumber").val(),
				 statusButton: vaStatusButton	,
				 url_address:$("#url_address").val(),
				 agent_browser:$("#agent_browser").val()
			}, function(result) {
				if ( result.vaStatusInsert == 'yes'){	
					var vnUserId = $("#userId").val();
					var vnSiteId = $("#siteId").val();

					var url = reporturl+"CS62000R.jsp?siteId="+vnSiteId+"&userId="+vnUserId+"&requestNumber="+result.RequestNumber;
					window.open(url);
					
					document.getElementById("msgSuccess").innerHTML = "ทำการบันทึกสำเร็จ";
					document.getElementById("inputAccont").disabled = false;
					$('#success_message').removeClass('hide');
					clearForm();
				}
				// set on top Screen
				$(document).ready(function() {
					  $("html,body").animate({scrollTop: 0}, 100);
				});
			});
		}
	} else {
		$("#inputAccont").focus();	
		$("#inputAccont").popover('show');
	}
}

//-------- radio selected
function calculateOnSelected(userSelected,options) {
	var vaRequestType = $('#inputRequestType').val();
	var vaAccount = document.getElementById("inputAccont").value;

	if ( vaStatusButton =='search_by_account'){
		if ( userSelected == 'vaCalculate'){
			$.getJSON('CS62000Srvl',{ selectedCalculateByAccount: userSelected, inputAccountPassJSon: vaAccount, dwlRequestType: vaRequestType}, function(result)	{
				writeHtmlDiv(result,options);
			});
		} else {
				document.getElementById("divCalculate").innerHTML = "<div id='divCalculate' class='form-group'></div>";
		}
	} else if( vaStatusButton =='search_by_request'){
		if ( userSelected == 'vaCalculate'){
			$.getJSON('CS62000Srvl',{ selectedCalculateByRequest: userSelected,inputAccountPassJSon: vaAccount,dwlRequestType: vaRequestType, inputRequestNumberPassJSon: $("#inputRequestNumber").val()}, function(result)	{
				writeHtmlDiv(result,options);
			});
		} else {
				document.getElementById("divCalculate").innerHTML = "<div id='divCalculate' class='form-group'></div>";
		}
	} else{
		$('input[name=rdo1][value=vaNotCalculate]').prop("checked",true);
		document.getElementById("divCalculate").innerHTML = "";
		
		if(options!==1){
			$("html,body").animate({scrollTop: 0}, 100);  
			document.getElementById("msgError").innerHTML = "ไม่มีการคิดเงิน ในคำร้องนี้";
			$('#error_message').removeClass('hide');
		}
	}
}

function writeHtmlDiv(result,options){
	var htmlDiv = '';
	vaRound = result.values.length;

	if(vaRound!=0){
		for ( var i = 0; i < result.values.length; i++) {
			htmlDiv += "<div class='form-group'>" +
							"<label class='col-sm-3 control-label'><span></span></label>" +
							"<div class='col-sm-4'><span id='vaReceiveDescription'>"+result.receiveCOde[i]+" "+result.messages[i]+"</span></div>" +
							"<div class='col-sm-2'>" +
								"<input type='text' class='form-control' id='inputFee"+i+"'"+" value='"+result.values[i]+"'"+"/>" +
								"<input type='hidden' id='hiddenReceiveCode"+i+"'"+" value='"+result.receiveCOde[i]+"'>"+
							"</div>" +
								"<div class='col-sm-1'><label   class='col-sm control-label'>บาท</label>" +
							"</div>" +
						"</div>";
		} ;
		$('input[name=rdo1][value=vaCalculate]').prop("checked",true);
		document.getElementById("divCalculate").innerHTML = htmlDiv;
	}else{
		$('input[name=rdo1][value=vaNotCalculate]').prop("checked",true);
		document.getElementById("divCalculate").innerHTML = "";
		
		if(options!==1){
			$("html,body").animate({scrollTop: 0}, 100);  
			document.getElementById("msgError").innerHTML = "ไม่มีการคิดเงิน ในคำร้องนี้";
			$('#error_message').removeClass('hide');
		}
	}
		
}

function loadProvince(click) {
	$.getJSON('CS62000Srvl', { province: "yes", process_type: "getData" }, function(result) {
		var options = '';
		options += '<option value="">-- เลือกจังหวัด --</option>';
		for (var i = 0; i < result.values.length; i++) {
			options += '<option value="' + result.values[i] + '">' + result.messages[i] + '</option>';
		}
	    $("select#inputProvinceCode").html(options);
	});
}

function loadDistrict(click) {
		var e = document.getElementById("inputProvinceCode");
	    $.getJSON("CS62000Srvl", {province: e.options[e.selectedIndex].value, district: "yes", process_type: "getData"}, function(result){
	    	var options = '';
			options += '<option value="">-- เลือกอำเภอ --</option>';
			for (var i = 0; i < result.values.length; i++) {
				options += '<option value="' + result.values[i] + '">' + result.messages[i] + '</option>';
			}
		    $("select#inputDistrictCode").html(options);
		    // set default to city
		    var options2 = '<option value="">-- เลือกตำบล --</option>';
			$("select#inputCityCode").html(options2);
	    }); 
}

function setDistrict(vaDistrict) {
	if ( vaDistrict != null){
		var e = document.getElementById("inputProvinceCode");
	    $.getJSON("CS62000Srvl", {province: e.options[e.selectedIndex].value, district: "yes", process_type: "getData"}, function(result){
	    	var options = '';
			options += '<option value="">-- เลือกอำเภอ --</option>';
			for (var i = 0; i < result.values.length; i++) {
				if (result.values[i] == vaDistrict){
					options += '<option value="' + result.values[i] + '" '+'selected'+'>' + result.messages[i] + '</option>';
				} else {
					options += '<option value="' + result.values[i] + '">' + result.messages[i] + '</option>';
				} 
			}
			 $("select#inputDistrictCode").html(options);
		});
	}
}

function loadCityCode(click) {
		var vaDistrict = document.getElementById("inputDistrictCode");
		var vaProvince = document.getElementById("inputProvinceCode");
	    $.getJSON("CS62000Srvl", {province: vaProvince.options[vaProvince.selectedIndex].value, 
	    	district: vaDistrict.options[vaDistrict.selectedIndex].value, city: "yes", process_type: "getData"}, function(result){
	    	var options = '';
			options += '<option value="">-- เลือกตำบล --</option>';
			for (var i = 0; i < result.values.length; i++) {
				options += '<option value="' + result.values[i] + '">' + result.messages[i] + '</option>';
			}
		    $("select#inputCityCode").html(options);
	    });
}

function setCityCode(vaCityCode, vaProvinceTemp,vaDistrictTemp) {
	if (vaCityCode != null){
	    $.getJSON("CS62000Srvl", {province: vaProvinceTemp, district: vaDistrictTemp, city: "yes"}, function(result){
	    	var options = '';
			options += '<option value="">-- เลือกตำบล --</option>';
			for (var i = 0; i < result.values.length; i++) {
				if (result.values[i] == vaCityCode){
					options += '<option value="' + result.values[i] + '" '+'selected'+'>' + result.messages[i] + '</option>';
				} else {
					options += '<option value="' + result.values[i] + '">' + result.messages[i] + '</option>';
				}
			}
		    $("select#inputCityCode").html(options);
	    });
	}
}

function loadRequestType() {
	$.getJSON('CS62000Srvl', { requestType: "yes" }, function(result) {
		var options = '';
		options += '<option value="">-- เลือก --</option>';
		for (var i = 0; i < result.values.length; i++) {
			options += '<option value="' + result.values[i] + '">' + result.values[i]+" "+result.messages[i] + '</option>';
		}
	    $("select#inputRequestType").html(options);
	});
}

function validateForm() {
	var error = false;
	$("#inputFName").popover('destroy');
	$("#inputAccont").popover('destroy');
	$("#inputHomeNumber").popover('destroy');
	$("#inputProvinceCode").popover('destroy');
	$("#inputDistrictCode").popover('destroy');
	$("#inputCityCode").popover('destroy');
	$("#inputRequestType").popover('destroy');
	$("#inputPostCode").popover('destroy');
	if (document.getElementById("inputFName").value == "") {
		$("#inputFName").focus();	
		$("#inputFName").popover('show');
		error = true;
	} 
	if ( document.getElementById("inputAccont").value == ""){
		$("#inputAccont").focus();	
		$("#inputAccont").popover('show');
		error = true;
	}
	if ( document.getElementById("inputRequestType").value == ""){
		$("#inputRequestType").focus();	
		$("#inputRequestType").popover('show');
		error = true;
	}
	if ( document.getElementById("inputHomeNumber").value == ""){
		$("#inputHomeNumber").focus();	
		$("#inputHomeNumber").popover('show');
		error = true;
	}
	if ( document.getElementById("inputPostCode").value == ""){
		$("#inputPostCode").focus();	
		$("#inputPostCode").popover('show');
		error = true;
	}
	if ( document.getElementById("inputProvinceCode").value == ""){
		$("#inputProvinceCode").focus();	
		$("#inputProvinceCode").popover('show');
		error = true;
	} else if (document.getElementById("inputDistrictCode").value == ""){
		$("#inputDistrictCode").focus();	
		$("#inputDistrictCode").popover('show');
		error = true;
	} else if (document.getElementById("inputCityCode").value == ""){
		$("#inputCityCode").focus();	
		$("#inputCityCode").popover('show');
		error = true;
	}
	if (error) return false;
	else return true;
}